package com.wyix.controller;

import com.wyix.domain.Book;
import com.wyix.service.BookService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author wangdx
 * @since 2025/8/26
 */
@RestController
@RequestMapping("/books")  // 接口前缀：/book-api/books
@RequiredArgsConstructor
public class BookController {
    private final BookService bookService;

    /**
     * 新增图书
     */
    @PostMapping
    public ResponseEntity<Book> addBook(@RequestBody Book book) {
        Book savedBook = bookService.addBook(book);
        return new ResponseEntity<>(savedBook, HttpStatus.CREATED);
    }

    /**
     * 按 ID 查询图书
     */
    @GetMapping("/{id}")
    public ResponseEntity<Book> getBookById(@PathVariable Long id) {
        Book book = bookService.getBookById(id);
        return ResponseEntity.ok(book);
    }

    /**
     * 模糊查询图书
     */
    @GetMapping("/search")
    public ResponseEntity<List<Book>> searchBooks(@RequestParam String bookName) {
        List<Book> books = bookService.searchBooksByTitle(bookName);
        return ResponseEntity.ok(books);
    }

    /**
     * 趣味接口：查询借阅排行榜前 10
     */
    @GetMapping("/top10")
    public ResponseEntity<List<Object[]>> getTop10BorrowedBooks() {
        List<Object[]> topBooks = bookService.getTop10BorrowedBooks();
        return ResponseEntity.ok(topBooks);
    }
}
